package com.sixmac.controller.backend;

import com.sixmac.common.DataTableFactory;
import com.sixmac.controller.common.CommonController;
import com.sixmac.core.Constant;
import com.sixmac.entity.SysUser;
import com.sixmac.service.OperaService;
import com.sixmac.service.RoleModulesService;
import com.sixmac.service.RolesService;
import com.sixmac.service.SysUserService;
import com.sixmac.utils.JsonUtil;
import com.sixmac.utils.Md5Util;
import com.sixmac.utils.RandomUtil;
import com.sixmac.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2016/4/2 0002.
 */
@Controller
@RequestMapping(value = "backend/sysUser")
public class SysUserController extends CommonController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RolesService rolesService;

    @Autowired
    private RoleModulesService roleModulesService;

    @Autowired
    private OperaService operaService;

    @RequestMapping("index")
    public String index() {
        return "backend/管理员列表";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     String account,
                     Integer roleId,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = getPageNum(start, length);
        Page<SysUser> page = sysUserService.page(account, roleId, pageNum, length);

        // 循环查找每个管理员的角色权限列表
        for (SysUser sysUser : page.getContent()) {
            sysUser.setRoleModuleList(roleModulesService.findListByRoleId(sysUser.getRole().getId()));
        }

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    @RequestMapping("/add")
    public String add(ModelMap model, Integer id) {
        if (id != null) {
            SysUser sysUser = sysUserService.getById(id);
            model.addAttribute("sysUser", sysUser);
        }
        return "backend/新增管理人员";
    }

    @RequestMapping("/save")
    @ResponseBody
    public Integer save(HttpServletRequest request,
                        Integer id,
                        Integer roleId,
                        String account,
                        String mobile) {
        try {
            if (roleId == Constant.ADMIN_ID) {
                return -1;
            }

            if (sysUserService.checkMobile(mobile)) {
                return -2;
            }

            SysUser sysUser = null;

            if (null == id) {
                sysUser = new SysUser();
            } else {
                sysUser = sysUserService.getById(id);
            }

            sysUser.setAccount(account);
            sysUser.setMobile(mobile);
            sysUser.setRole(rolesService.getById(roleId));
            sysUser.setStatus(Constant.STATUS_YES);

            if (null == id) {
                String password = RandomUtil.generateShortUuid();
                sysUser.setPassword(Md5Util.md5(password));

                // TODO 将密码发送到该用户手机上

                sysUser.setCreateTime(new Date());
                sysUserService.create(sysUser);
            } else {
                sysUserService.update(sysUser);
            }

            operaService.addOperaInfo(request, (null == id ? "新增" : "修改") + "管理员 " + sysUser.getAccount());

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("delete")
    @ResponseBody
    public Integer delete(HttpServletRequest request, Integer id) {
        if (id != null) {
            sysUserService.deleteById(request, id);
            return 1;
        }
        return 0;
    }

    @RequestMapping("/batchDel")
    @ResponseBody
    public Integer batchDel(HttpServletRequest request, String ids) {
        try {
            int[] arrayId = JsonUtil.json2Obj(ids, int[].class);
            sysUserService.deleteAll(request, arrayId);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("/batchRet")
    @ResponseBody
    public Integer batchRet(HttpServletRequest request, String ids) {
        try {
            int[] arrayId = JsonUtil.json2Obj(ids, int[].class);
            sysUserService.retAll(request, arrayId);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("/batchChangeStatus")
    @ResponseBody
    public Integer batchChangeStatus(HttpServletRequest request, String ids, Integer status) {
        try {
            int[] arrayId = JsonUtil.json2Obj(ids, int[].class);
            sysUserService.batchChangeStatus(request, arrayId, status);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @RequestMapping("resetPwd")
    @ResponseBody
    public Integer resetPwd(HttpServletRequest request, Integer id) {
        SysUser sysUser = sysUserService.getById(id);
        if (null != sysUser) {
            if (!StringUtils.isNotEmpty(sysUser.getMobile())) {
                return -1;
            }

            String password = RandomUtil.generateShortUuid();
            sysUser.setPassword(Md5Util.md5(password));
            sysUserService.update(sysUser);

            // TODO 将密码发送到该用户手机上

            operaService.addOperaInfo(request, "重置管理员 " + sysUser.getAccount() + " 的登录密码");

            return 1;
        }
        return 0;
    }

    @RequestMapping("updateStatus")
    @ResponseBody
    public Integer updateStatus(HttpServletRequest request, Integer id, Integer status) {
        SysUser sysUser = sysUserService.getById(id);
        if (null != sysUser) {
            sysUser.setStatus(status);
            sysUserService.update(sysUser);

            operaService.addOperaInfo(request, (status == Constant.STATUS_YES ? "启用" : "禁用") + "管理员 " + sysUser.getAccount());

            return 1;
        }
        return 0;
    }
}
